import { delCart, getCartList, updateCartCount } from '@/api/cart'
import Vue from 'vue'
import { Toast } from 'vant'

Vue.use(Toast)
export default {
  namespaced: true, // 为了保证数据的独立性，写成一个函数的形式，但是返回的是对象
  // 相当于 state:{}
  state () {
    return {
      cartList: []
    }
  }, // 所有mutations里面的方法，第一个参数都是state，第二个才是形参payload
  // 封装定义修改state的方法，里面更多的是赋值
  // 定义完成之后，去页面调用，把需要存的数据（实参）拿过来给赋值给state
  mutations: {
    setCartList (state, arr) {
      state.cartList = arr
    },
    toggleCheck (state, id) {
      const good = state.cartList.find(item => item.goods_id === id)
      good.isChecked = !good.isChecked
    },
    setAllSelect (state, bool) {
      state.cartList.forEach(item => {
        item.isChecked = bool
      })
    },
    setChangeCount (state, obj) {
      const goods = state.cartList.find(item => item.goods_id === obj.goodsId)
      goods.goods_num = obj.goodsNum
    }
  },
  actions: {
    async getCartListAction (store) {
      const res = await getCartList()
      console.log(res)
      // 后台返回的数据中，不包含复选框的选中状态，为了实现将来的功能，
      // 需要手动维护数据，给每一项加一个isChecked状态，标记当前商品是否选中
      res.data.list.forEach(item => {
        item.isChecked = true
      })
      console.log(res)
      store.commit('setCartList', res.data.list)
    },
    async changeCountAction (store, obj) {
      const {
        goodsNum,
        goodsId,
        goodsSkuId
      } = obj
      const res = await updateCartCount(goodsNum, goodsId, goodsSkuId)
      console.log(res)
      // 本地修改
      store.commit('setChangeCount', {
        goodsNum,
        goodsId
      })
    },
    async delAction (store) {
      const cartIds = store.getters.selectGoods.map(item => item.id)
      const res = await delCart(cartIds)
      console.log(res)
      Toast('删除成功')
      // 调模块内部的actions
      store.dispatch('getCartListAction')
    }
  },
  getters: {
    selectGoods (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    total (state) {
      return state.cartList.reduce((t, item) => {
        if (item.isChecked) {
          return t + item.goods_num
        } else {
          return t
        }
      }, 0)
    },
    totalPrice (state) {
      return state.cartList.reduce((count, item) => {
        if (item.isChecked) {
          // 选中的，需要累加
          return count + item.goods_num * item.goods.goods_price_min
        } else {
          // 没选中的，不需要累加
          return count
        }
      }, 0)
    },
    // 全选
    allSelect (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }

}
